var express = require('express');
const accountModel = require('../../modules/accountModel');
const dayjs = require('dayjs')
var customParseFormat = require('dayjs/plugin/customParseFormat')


var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
	res.render('index', {
		title: 'Express'
	});
});
router.get('/account', (req, res, next) => {
	accountModel.find().sort({
		time: -1
	}).lean().exec().then(data => {
		data.forEach(item => {
			let timestr = dayjs(new Date(item.time)).format('YYYY-MM-DD')
			item.time = timestr
		})
		res.json({
			code: '0000',
			msg: '成功',
			data: data
		})
	}, err => {
		res.json({
			code: '1001',
			msg: '读取数据库失败',
			data: null
		})
	})
})
router.get('/account/:id', (req, res, next) => {
	accountModel.findById({
		_id: req.params.id
	}).lean().exec().then(data => {
		let timestr = dayjs(new Date(data.time)).format('YYYY-MM-DD')
		data.time = timestr
		res.json({
			code: '0000',
			msg: '成功',
			data: data
		})
	}, err => {
		res.json({
			code: '1001',
			msg: '查找失败，该数据不存在',
			data: null
		})
	})
})
router.get('/account/create', (req, res, next) => {
	res.render('createAccount')
})
router.post('/account/create', (req, res, next) => {
	console.log(req.body)
	//添加到mongo中 
	dayjs.extend(customParseFormat)
	accountModel.create({
		...req.body,
		time: dayjs(req.body.time).toDate()
	}).then((data) => {
		res.json({
			code: '0000',
			msg: '添加成功',
			data
		})
	}, (err) => {
		res.json({
			code: '1002',
			msg: '添加失败',
			data: null
		})
	})


})
router.delete('/account/:id', (req, res, next) => {
	console.log(req.params.id)
	accountModel.deleteOne({
		_id: req.params.id
	}).then(data => {
		res.json({
			code: '0000',
			msg: '删除成功',
			data: data
		})
	}).catch(err =>
		res.json({
			code: '1003',
			msg: '删除失败',
			data: null
		})
	)


})
router.patch('/account/:id', (req, res, next) => {
	console.log(req.params.id)
	accountModel.updateOne({
		_id: req.params.id
	}, req.body).then(data => {
		//再次查询，返回新数据
		accountModel.findById({
			_id: req.params.id
		}).lean().exec().then(newData => {
			let timestr = dayjs(new Date(newData.time)).format('YYYY-MM-DD')
			newData.time = timestr
			res.json({
				code: '0000',
				msg: '更新成功',
				data: newData
			})
		}).catch(err => res.json({
			code: '1005',
			msg: '更新成功,但是重新查询失败',
			data: null
		}))
	}).catch(err =>
		res.json({
			code: '1004',
			msg: '更新失败',
			data: null
		})
	)


})
module.exports = router;